import React, {useCallback} from 'react';

import {Button, Card, DatePicker, Dialog, Field, Input, List, Message, Pagination, Select, Table} from '@alifd/next';
import {useFusionTable, useSetState} from 'ahooks';

import {request,Link,useLocation } from 'ice';
import moment, {Moment} from 'moment';
import EmptyBlock from './EmptyBlock';
import ExceptionBlock from './ExceptionBlock';
import DialogOperation from './DialogOperation';
import {ActionType, OperaitionProps} from './Operation';

import styles from './index.module.scss';

const {RangePicker, MonthPicker, YearPicker, WeekPicker} = DatePicker;

interface queryData {
  orderByLevel: boolean;
  machineCode: string;
  phoneNum: string;
  code: string;
  userId: string;
  latitude:string;
  longitude:string;
  mvId:number;
  timeLimit:number;
};

const defaultQueryData: queryData = {
  longitude:'116.450586',
  latitude:'39.948647',
  orderByLevel: true,
  machineCode: '',
  phoneNum: '',
  code: '',
  userId: '',
  mvId:1,
  timeLimit:1
}



interface ColumnWidth {
  userId: number;
  userName: number;
  userPic: number;
  level: number;
  inviteCode: number;
  phoneNum: number;
  machineCode: number;
  creat: number;
  lastVisit: number;
  totalWithdrawal: number;
  withdrawalCount: number;
  balance: number;
  fatherId: number;
  operation: number;
}

interface DialogState {
  columnWidth: ColumnWidth;
  optCol: any;
  actionType: ActionType;
  actionVisible: boolean;
}

const defaultColumnWidth: ColumnWidth = {
  userId: 200,
  userName: 150,
  userPic: 100,
  level: 70,
  inviteCode: 220,
  phoneNum: 200,
  machineCode: 200,
  creat: 250,
  lastVisit: 250,
  totalWithdrawal: 100,
  withdrawalCount: 100,
  balance: 100,
  fatherId: 250,
  operation: 100,

};



const UserSimpleInfoListComponment: React.FC = () => {

  const [mvLeable, setMvLeable] = useSetState(false);
  const [mvLeableInit, setMvLeableInit] = useSetState(false);
  const [mvLeableData, setMvLeableData] = useSetState([]);
  const [mvLeableDataCount, setMvLeableDataCount] = useSetState(0);
  const [farm, setFarm] = useSetState<queryData>(defaultQueryData);

  const [dShow, setDShow] = useSetState({
    show:false,
    source:{}
  });
  
  const location = useLocation();

  if(location.state?.value?.id){
    farm.mvId=location.state?.value?.id
  }

  const getTableData = (
    {current, pageSize}: { current: number; pageSize: number },
    formData: {
      status: 'normal' | 'empty' | 'exception';
      orderByLevel: true | false;
      machineCode: string;
      phoneNum: string;
      code: string;
      userId: string;
    }
  ): Promise<any> => {
    if (!formData.status || formData.status === 'normal') {
      let query = `current=${current}&size=${pageSize}`;
  
      defaultQueryData.userId = '';
      Object.entries(farm).forEach(([key, value]) => {
        if (value) {
          query += `&${key}=${value}`
        }
      });
      const data = request({
        url: `/v1/movie/info/?${query}`,
        method: 'get',
      });
      return data.then(res => {
        return {
          list: res.data.records,
          total: res.data.total
        }
      })
    }
    if (formData.status === 'empty') {
      return Promise.resolve([]);
    }
    if (formData.status === 'exception') {
      // console.log(formData);
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          reject(new Error('data exception'));
        }, 1000);
      });
    }
  
    return Promise.resolve([]);
  };



  async function dOnOk(){
    
      const data = await request({
        url: `/v1/movie/buy/`,
        method: 'post',
        data:dShow.source
      });
      console.log(data);
      if(data?.statusCode==200){
        Message.success('购买成功');
        dOnonClose();
        reset();
      }
  }

  async function getMvLeable(){
    if(!mvLeable){
      setMvLeable(false);
      const data = await request({
        url: `/v1/movie/label/`,
        method: 'get',
      });
      setMvLeableData(data.data.list);
      setMvLeableDataCount(data.data.count)
      // console.log(data.data.count);

      return data.data
      // data.then(res =>{
      //   setMvLeableData(res.data);
      // })
    }
  }
  getMvLeable()
  const dataSource2=new Array(10);
  const dataSource1= [
    {value: 1, label: '今日'},
    {value: 2, label: '三日内'},
    {value: 3, label: '五日内'}];

    
    if(mvLeableData[0]){
      for(var num = 0;num<10;num++){
        // console.log(mvLeableData[num]);
        if(mvLeableData[num]){
          dataSource2.push(mvLeableData[num]);
        }
      }
    }
  
  
  const [state, setState] = useSetState<DialogState>({
    columnWidth: defaultColumnWidth,
    optCol: null,
    actionType: 'preview',
    actionVisible: false,
  });
  const {actionVisible, columnWidth, optCol} = state;
  const field = Field.useField([]);
  const {paginationProps, tableProps, search, error, refresh} = useFusionTable(getTableData, {
    field,
  });

  const {reset} = search;

  const onResizeChange = (dataIndex: keyof typeof defaultColumnWidth, width: number) => {
    const newWidth = {
      ...columnWidth,
    };
    newWidth[dataIndex] += width;
    setState({columnWidth: newWidth});
  };

  const operationCallback = useCallback(({actionType, dataSource}: OperaitionProps): void => {
    setState({
      actionType,
      optCol: dataSource,
      actionVisible: true,
    });
  }, [setState]);

  const handleCancel = useCallback((): void => {
    setState({actionVisible: false});
  }, [setState]);

  const handleOk = useCallback((): void => {
    const {actionType, optCol} = state;
    if (actionType === 'preview') {
      handleCancel();
      return;
    }
    Message.success(actionType === 'add' ? '添加成功!' : '编辑成功!');
    reset();
    handleCancel();
  }, [handleCancel, reset, state]);

  const handleDelete = useCallback((data: any) => {
    if (!data) {
      return;
    }
    Dialog.confirm({
      title: '删除提醒',
      content: `确定删除 ${data.name.last} 吗`,
      onOk() {
        Message.success(`${data.name.last} 删除成功!`);
        reset();
      }
    });
  }, [reset]);

  const cast4 = value => {
    if (value)
      return "已购买"
    else
     return '购买'
  }

  const cellOperation = (...args: any[]): React.ReactNode => {
    const record = args[2];
    return (
      <div>
        <Button
          type="primary"
          disabled={record.hasBuy}
          onClick={() => dOnOpen({actionType: 'edit', dataSource: record})}
        >
          {cast4(record.hasBuy)}
        </Button>
        &nbsp;&nbsp;
      </div>
    );
  };

  const cast5 = (...args: any[]): React.ReactNode => {
    const record = args[2];
    return record.nowCount +"/"+record.maxCount
  };


  const cast2 = value => {
    if (value)
      return Number(value).toFixed(1)+"km"
    else
     return ''
  }
  const cast3 = value => {
    if (value)
      return "￥"+ Number(value) +"起"
    else
     return ''
  }
  const cast6 =  (...args: any[]) => {
    const record = args[2];
    console.log(record);
    return record.startTime?.replace("T"," ")
  };





  const onUserIdChange = value => {
    setFarm({
      latitude:value
    })
  }
  const onPhoneNumChange = value => {
    setFarm({
      longitude:value
    })
    // farm.longitude = value;
  }
  const onMachineCodeChange = value => {
    setFarm({
      mvId:value
    })
    farm.mvId = value;
  }
  const onCodeChange = value => {
    setFarm({
      timeLimit:value
    })
    // farm.timeLimit = value;
  }


  const [searchDate, setSearchDate] = useSetState<Moment[]>([moment().subtract(1, 'weeks'), moment()]);
  const onChange = val => {
    setSearchDate(val);
  }

  const dOnonClose = () => {
    setDShow({show:false})
  }
  const dOnOpen = value => {
    console.log(value.dataSource);
    setDShow({
      show:true,
      source:value.dataSource
    })
  }

  return (

    
    <div className={styles.DialogTable}>

      <Dialog  
          title="确认购买"
          visible={dShow.show}
          onOk={dOnOk}
          onCancel={dOnonClose}
          onClose={dOnonClose}>
          <Input addonBefore="电影名称" size='large' readOnly	 hasBorder={false} placeholder="" value={"《"+dShow?.source?.mvName+"》"}/>
          <Input addonBefore="电影院名称"  size='large' readOnly	 hasBorder={false} placeholder="" value={dShow?.source?.name}/>
          <Input addonBefore="电影厅名称"  size='large' readOnly	 hasBorder={false} placeholder="" value={dShow?.source?.mhName}/>
          <Input addonBefore="观影时间"  size='large' readOnly	 hasBorder={false} placeholder="" value={dShow?.source?.startTime}/>
          <Input addonBefore="票价"  size='large' readOnly	 hasBorder={false} placeholder="" value={dShow?.source?.price+"元"}/>
      </Dialog>

      {/* header={<div>用户简单信息分页查询</div>} */}
      <List >
        <List.Item>
          <div>
          {/* 是否按照等级排序：
            <Select defaultValue="是" aria-labelledby="state of project" onChange={onOrderByLevelChange}>
              <Select.Option id="orderByLevelTrue" value="true">是</Select.Option>
              <Select.Option id="orderByLevelFalse" value="false">否</Select.Option>
            </Select> */}
            <Input label="精度" placeholder="请输入精度" defaultValue={"116.450586"} onChange={onUserIdChange}/>
            <Input label="维度" placeholder="请输入维度" defaultValue={"39.948647"} onChange={onPhoneNumChange}/>
            {/* <Select placeholder="Select Province" dataSource={provinceData} value={province} onChange={this.handleProvinceChange} /> */}
            <Select label="电影名:" dataSource={dataSource2} onChange={onMachineCodeChange}  value={farm.mvId}/>
            <Select label="观看日期:"  dataSource={dataSource1} onChange={onCodeChange} value={farm.timeLimit} />
            <Button
              type="primary"
              onClick={() => reset()}>
              搜索</Button>
          </div>
        </List.Item>


      </List>
      <Card free>
        <Card.Content>
          <Table
            {...tableProps}
            onResizeChange={onResizeChange}
            emptyContent={error ? <ExceptionBlock onRefresh={refresh}/> : <EmptyBlock/>}
            primaryKey="email"
          >

            <Table.Column title="电影院名次" dataIndex="name" resizable width={columnWidth.userId}/>
            <Table.Column title="详细地址" dataIndex="address" resizable width={columnWidth.userName}/>
            <Table.Column title="已购票数/最大容量" dataIndex="maxCount" resizable width={columnWidth.userPic} cell={cast5} />
            <Table.Column title="价格" dataIndex="price" resizable width={columnWidth.level} cell={cast3}/>
            <Table.Column title="放映厅名称" dataIndex="mhName" resizable width={columnWidth.inviteCode}/>
            <Table.Column title="距离(千米)" dataIndex="distance" resizable width={columnWidth.phoneNum} cell={cast2}/>
            <Table.Column title="最近场次" dataIndex="startTime" resizable width={columnWidth.machineCode} cell={cast6}/>
            <Table.Column title="操作" resizable width={columnWidth.operation} cell={cellOperation}/>
          </Table>
          <Pagination pageSizeList={[10, 20]} pageSizeSelector="filter" style={{marginTop: 16, textAlign: 'right'}}
                      totalRender={total => <>共 <Button text
                                                        type="primary">{total}</Button> 个记录</>}  {...paginationProps} />
        </Card.Content>
      </Card>
      <DialogOperation
        visible={actionVisible}
        actionType={state.actionType}
        dataSource={optCol}
        onOk={handleOk}
        onClose={handleCancel}
        onCancel={handleCancel}
      />
    </div>
  );
}


export default UserSimpleInfoListComponment;
